/**
 * @author dsbatista
 * 
 */

package reaction.news.index;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collection;

import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

import reaction.news.Definitions;
import reaction.news.db.MySQLConnection;

public class CreateIndex {

	static Collection<Document> news = new ArrayList<Document>();
		
	public static void createPoliticians() throws Exception{
		
		Connection connection = MySQLConnection.getConnection(Definitions.username, Definitions.password, "jdbc:mysql://reactionvm01/news-entities");
		
		// Get all politicians
		String SQLString = "SELECT * FROM power_entities";
		
		Statement stmt = connection.createStatement();
		ResultSet rs = stmt.executeQuery(SQLString);
		
		while (rs.next()) {
			
			// Create a Politician
			int id = rs.getInt(1);
			String power_URI = rs.getString(2);
			String name = rs.getString(3);
			
			// Get all the news associated with that Politician
			// Creates  a Document (Lucene) with all the news vocabulary associated with the Politician 
			Politician p = new Politician(id,name,power_URI);
			Document d = p.getNews();
			
			// Add the Document to be later indexed
			news.add(d);
		}
		
		rs.close();
		stmt.close();
		connection.close();
		
	}
	
	public static int createIndex() {
		
		IndexWriterConfig indexCfg = new IndexWriterConfig(Version.LUCENE_35, Definitions.analyzer);
		
		try {			
			
			Definitions.newsIndexDirectory = FSDirectory.open(new File("publico.pt"));
			IndexWriter indexW = new IndexWriter(Definitions.newsIndexDirectory,indexCfg);
			indexW.addDocuments(news, Definitions.analyzer);
			indexW.commit();
			indexW.close();
			return indexW.numDocs();
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return 0;	
	}
	
	
	public static int start() throws Exception{
		createPoliticians();
		int num_docs = createIndex();
		return num_docs;
	}
}



